import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '@/views/HomeView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView
    },
    {
  path: '/cashier',
  name: 'cashier',
  component: () => import('@/components/home/CashierView.vue'),
  meta: { requiresAuth: true }
},
    {
      path: '/login',
      name: 'login',
      redirect: '/'
    },
    {
      path: '/register',
      name: 'register',
      redirect: '/'
    },
    {
      path: '/collection/:id',
      name: 'collectionDetail',
      component: () => import('@/views/CollectionDetail.vue')
    },
    //搜索界面
     {
      path: '/search', 
      name: 'search',
      component: () => import('../views/SearchView.vue')
    },
    //访客查看用户页面
    {
      path: '/visitor/:id',
      name: 'visitor',
      component: () => import('../views/VisitorView.vue')
    },
    //商品详情页面
    {
      path: '/detailShop/:goodsId', 
      name: 'detailShop',
      component: () => import('../components/shop/DetailShop.vue')
    },
    //店铺详情页面
    {
      path: '/detailMerchant/:sellerUserId', 
      name: 'detailMerchant',
      component: () => import('../components/shop/DetailMerchant.vue')
    },
    {
  path: '/user/orders',
  name: 'userOrders',
  component: () => import('@/components/shop/UserOrders.vue'),
  meta: { requiresAuth: true }
},
// 在路由配置中添加
{
  path: '/Refund',
  name: 'Refund',
  component: () => import('@/components/shop/RefundPage.vue'),
  meta: { title: '退款管理' }
},
    // 审核端路由
    {
      path: '/auditor',
      component: () => import('@/views/auditor/AuditorLayout.vue'),
      meta: { requiresAuth: true, role: 'auditor' },
      children: [
        {
          path: '',
          name: 'auditorDashboard',
          component: () => import('@/views/auditor/Dashboard.vue')
        },
        {
          path: 'content',
          name: 'auditorContent',
          component: () => import('@/views/auditor/ContentAudit.vue')
        },
        {
          path: 'comments',
          name: 'auditorComments',
          component: () => import('@/views/auditor/CommentAudit.vue')
        },
        {
          path: 'merchants',
          name: 'auditorMerchants',
          component: () => import('@/views/auditor/MerchantAudit.vue')
        },
        {
          path: 'logs',
          name: 'auditorLogs',
          component: () => import('@/views/auditor/AuditLogs.vue')
        },
        {
          path: 'statistics',
          name: 'auditorStatistics',
          component: () => import('@/views/auditor/AuditStatistics.vue')
        },
        {
          path: 'profile',
          name: 'auditorProfile',
          component: () => import('@/views/auditor/Profile.vue')
        }
      ]
    },
    // 商户端路由
    {
      path: '/merchant',
      component: () => import('@/views/merchant/MerchantLayout.vue'),
      meta: { requiresAuth: true, role: 'merchant' },
      children: [
        {
          path: '',
          name: 'merchantDashboard',
          component: () => import('@/views/merchant/Dashboard.vue')
        },
        {
          path: 'courses',
          name: 'merchantCourses',
          component: () => import('@/views/merchant/CourseList.vue')
        },
        {
          path: 'create',
          name: 'merchantCourseCreate',
          component: () => import('@/views/merchant/CourseCreate.vue')
        },
        {
          path: 'edit/:id',
          name: 'merchantCourseEdit',
          component: () => import('@/views/merchant/CourseEdit.vue')
        },
        {
          path: 'orders',
          name: 'merchantOrders',
          component: () => import('@/views/merchant/OrderList.vue')
        },
        {
          path: 'media',
          name: 'merchantMedia',
          component: () => import('@/views/merchant/MediaUpload.vue')
        },
        {
          path: 'settings',
          name: 'merchantSettings',
          component: () => import('@/views/merchant/ShopSettings.vue')
        },
      ]
    },
    // 管理员端路由
    {
        path: '/admin',
        name: 'admin',
        component: () => import('@/views/admin/AdminLayout.vue'),
        children: [
          {
            path: '',
            name: 'adminDashboard',
            component: () => import('@/views/admin/Dashboard.vue'),
            meta: { title: '数据概览' }
          },
          {
            path: 'users',
            name: 'adminUsers',
            component: () => import('@/views/admin/UserManagement.vue'),
            meta: { title: '用户管理' }
          },
          {
            path: 'roles',
            name: 'adminRoles',
            component: () => import('@/views/admin/RoleManagement.vue'),
            meta: { title: '角色管理' }
          },
          {
            path: 'permissions',
            name: 'adminPermissions',
            component: () => import('@/views/admin/PermissionManagement.vue'),
            meta: { title: '权限管理' }
          },
          {
          path: 'worksReview',
          name: 'adminWorksReview',
          component: () => import('@/views/admin/WorksReview.vue')
        },
        {
            path: 'depts',
            name: 'adminDepts',
            component: () => import('@/views/admin/DeptManagement.vue'),
            meta: { title: '部门管理' }
          },
          {
            path: 'menus',
            name: 'adminMenus',
            component: () => import('@/views/admin/SystemSettings.vue'),
            meta: { title: '菜单管理' }
          },
          {
            path: 'courses',
            name: 'adminCourses',
            component: () => import('@/views/admin/CourseManagement.vue'),
            meta: { title: '课程管理' }
          },
          {
            path: 'orders',
            name: 'adminOrders',
            component: () => import('@/views/admin/OrderManagement.vue'),
            meta: { title: '订单管理' }
          },
          {
            path: 'products',
            name: 'adminProducts',
            component: () => import('@/views/admin/ProductManagement.vue'),
            meta: { title: '商品管理' }
          },
          {
            path: 'assignments',
            name: 'adminAssignments',
            component: () => import('@/views/admin/AssignmentManagement.vue'),
            meta: { title: '作业管理' }
          },
          {
            path: 'exams',
            name: 'adminExams',
            component: () => import('@/views/admin/ExamManagement.vue'),
            meta: { title: '考试管理' }
          },
          {
            path: 'settings',
            name: 'adminSettings',
            component: () => import('@/views/admin/SystemSettings.vue'),
            meta: { title: '系统设置' }
          },
          {
            path: 'AllData',
            name: 'adminData',
            component: () => import('@/views/admin/Dashboard.vue'),
            meta: { title: '数据概览' }
          }
        ]
      },
    // 404页面
    {
      path: '/:pathMatch(.*)*',
      name: 'notFound',
      component: () => import('@/views/NotFound.vue')
    }
  ]
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    // 从localStorage检查登录状态，避免在路由守卫中使用store
    const token = localStorage.getItem('token')
    const userInfo = localStorage.getItem('userInfo')
    
    if (!token || !userInfo) {
      // 未登录，跳转到首页
      next('/')
      return
    }
    
    // 检查角色权限
    const requiredRole = to.meta.role as string
    if (requiredRole) {
      try {
        const user = JSON.parse(userInfo)
        if (user.role !== requiredRole) {
          // 角色不匹配，跳转到首页
          next('/')
          return
        }
      } catch (error) {
        console.error('解析用户信息失败:', error)
        next('/')
        return
      }
    }
  }
  
  next()
})

export default router
